package com.evosoft.dao;

import com.evosoft.excepciones.NotEntityFoundException;
import com.evosoft.model.Empresa;
import com.evosoft.model.Tipo;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class EmpresaDAO extends GenericDao<Empresa>{

	
	private static final long serialVersionUID = 1L;
	private static EmpresaDAO instance;

    public EmpresaDAO() {
        super(Empresa.class);
    }

    public synchronized static EmpresaDAO getInstance() {
        if(instance == null){
            instance = new EmpresaDAO();
        }
        
        return instance;
    }

    public List<Empresa> obtenerEmpresas(int id, EntityManager em) throws NotEntityFoundException {
        Query query = em.createQuery("SELECT e FROM Empresa e WHERE e.tipo.id=:id");
        query.setParameter("id", id);
        
        List<Empresa> entity = new ArrayList<Empresa>();

        try {
            entity = (List) query.getResultList();
        } catch (Exception e) {
        	throw (new NotEntityFoundException());
        }

        return entity;
    }

    
    public List<Empresa> obtenerEmpresasDependientes(int id, EntityManager em) throws NotEntityFoundException {
        Query query = em.createQuery("SELECT e FROM Empresa e WHERE e.superior=:id");
        query.setParameter("id", id);
        
        List<Empresa> entity = new ArrayList<Empresa>();

        try {
            entity = (List) query.getResultList();
        } catch (Exception e) {
        	throw (new NotEntityFoundException());
        }

        return entity;
    }

    public int obtenerUltimaEmpresaCreada(EntityManager em) {
        Query query = em.createQuery("SELECT MAX(e.id) FROM Empresa e");
        int max = (Integer) query.getSingleResult();
        return max;
    }

    public Empresa obtenerEmpresaPorNit(String nit, EntityManager em) throws NotEntityFoundException {
        Query query = em.createQuery("SELECT e FROM Empresa e WHERE e.nit=:nit");
        query.setParameter("nit", nit);
        Empresa entity = new Empresa();
        try {
                entity = (Empresa) query.getSingleResult();
        } catch (Exception e) {
        	throw (new NotEntityFoundException());
        }
        return entity;
    }
	
	
}
